# -*- encoding=utf8 -*-
import wx
import images
import wx.html
import time
import os

import ipaddr

class SketchAbout(wx.Dialog):
    text = '''
<html>
<body bgcolor="#ACAA60">
<center><table bgcolor="#455481" width="100%" cellspacing="0"
cellpadding="0" border="1">
<tr>
    <td align="center"><h1>Sketch!</h1></td>
</tr>
</table>
</center>
<p><b>Sketch</b> is a demonstration program for <b>wxPython In Action</b>
Chapter 7.  It is based on the SuperDoodle demo included with wxPython,
available at http://www.wxpython.org/
</p>

<p><b>SuperDoodle</b> and <b>wxPython</b> are brought to you by
<b>Robin Dunn</b> and <b>Total Control Software</b>, Copyright
&copy; 1997-2006.</p>
</body>
</html>
'''

    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, u'帮助文档',
                          size=(440, 400) )

        html = wx.html.HtmlWindow(self)
        html.SetPage(self.text)
        button = wx.Button(self, wx.ID_OK, u"关闭")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(html, 1, wx.EXPAND|wx.ALL, 5)
        sizer.Add(button, 0, wx.ALIGN_CENTER|wx.ALL, 5)

        self.SetSizer(sizer)
        self.Layout()

# 显示Panel
class DispPanel(wx.Panel):
    def __init__(self, parent, ID, window):
        wx.Panel.__init__(self, parent, ID, style=wx.RAISED_BORDER)
        self.window = window
        usrLabel = wx.StaticText(self, -1, "Usr:")
        usrText = wx.TextCtrl(self, -1, "root", size=(60,-1))
        usrText.SetInsertionPoint(3)
        
        pwdLabel = wx.StaticText(self, -1, "Pwd:")
        pwdText = wx.TextCtrl(self, -1, "12345", size=(60,-1), style=wx.TE_PASSWORD)

        self.button = wx.Button(self, -1, u"登陆", pos=(0,20))
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
        self.button.SetDefault()

        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([usrLabel, usrText, pwdLabel, pwdText, self.button])
        self.SetSizer(sizer)
        
    def OnClick(self, event):
        self.button.SetLabel(u"已登陆")
        

# 显示Window
class DispWindow(wx.Window):
    def __init__(self, parent, ID):
        wx.Window.__init__(self, parent, ID)
        self.SetBackgroundColour("White")
        sText = wx.StaticText(self, -1, "This is static text", (0, 10))
        sText.SetForegroundColour('black')
        sText.SetBackgroundColour('green')

# 顶层frame
class TopFrame(wx.Frame):
    
    def __init__(self, parent):
        #print 'Frame.__init__'
        #note: 参数传递有默认顺序，形参可以为空
        #比如__init__形参self,parent,title
        #但wx.Frame.__init__参数是有顺序的，self, parent, id, title,
        #不能漏掉id，直接填title
        self.filename = ""
        wx.Frame.__init__(self, parent, -1, u'工作台')
        self.SetMinSize((640,480)) #设置Frame最小大小
        self.SetSize((640, 480))   #设置默认大小，如果只设最小，不设默认，则动一下才会变大
        #如果我想放在屏幕中间怎么搞？
        
        # ---------------- 窗口 ----------------
        self.disp_window = DispWindow(self, -1)
        
        # ---------------- 画板 ----------------
        #panel = wx.Panel(self)
        self.disp_panel = DispPanel(self, -1, self.disp_window)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(self.disp_window, 1, wx.EXPAND)
        box.Add(self.disp_panel, 0, wx.EXPAND) #box.Add的顺序决定显示的左右
        self.SetSizer(box)


        # ---------------- 菜单栏 ----------------
        menuBar = wx.MenuBar()
        menu_mFile = wx.Menu()
        menuBar.Append(menu_mFile, u"文件")
        mItem_save = menu_mFile.Append(wx.NewId(), u"保存log", "")
        self.Bind(wx.EVT_MENU, self.OnSave, mItem_save)
        
        mItem_exit = menu_mFile.Append(wx.NewId(), u"退出", "")
        self.Bind(wx.EVT_MENU, self.OnCloseMe, mItem_exit) #绑定菜单事件
        
        menu_mTool = wx.Menu()
        menuBar.Append(menu_mTool, u"设置")
        menu_mTool.Append(wx.NewId(), "TFT&P", "TFTP Server") # TFTP Server会显示在状态栏，&表示快捷键
        menu_mTool.Append(wx.NewId(), "&Telnet", "")
        menu_mTool.AppendSeparator() # 分割线
        menu_mTool.Append(wx.NewId(), "Serial", "")
        
        menu_mHelp = wx.Menu()
        menuBar.Append(menu_mHelp, u"帮助")
        #menu_mAbout = wx.Menu()
        #menuBar.Append(menu_mAbout, u"关于")
        mItem_help = menu_mHelp.Append(wx.NewId(), "Help")#, "")
        mItem_about = menu_mHelp.Append(wx.NewId(), "About")#, "")
        self.Bind(wx.EVT_MENU, self.ShowHelp, mItem_help)
        self.Bind(wx.EVT_MENU, self.ShowAbout, mItem_about)
        
        # 显示菜单栏
        self.SetMenuBar(menuBar)
        
        # ---------------- 工具栏 ----------------
        toolBar = self.CreateToolBar()
        toolBar.AddSimpleTool(wx.NewId(), images.getNewBitmap(), "TFTP", "tips for TFTP")
        toolBar.Realize() #显示工具栏，必需
        
        # ---------------- 状态栏 ----------------
        statusBar = self.CreateStatusBar()
        statusBar.SetFieldsCount(3)
        #statusBar.SetStatusWidths([-1, -2, -3])
        self.statusBar = statusBar #在TopFrame的子函数中引用self.statusBar必须要
        
        #获取IP地址
        statusBar.SetStatusText(ipaddr.GetIP(), 1)
        #开启定时器，获取当前系统时间
        self.timer = wx.PyTimer(self.Notify)
        self.timer.Start(1000)
        self.Notify()
        
        # ---------------- 临时调试代码 ----------------
        # ---------------- 按钮 ----------------
        #button = wx.Button(panel, label='Close', pos=(0,0), size=(50,30))
        #绑定button单击事件
        #self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button)
    
        # ---------------- 消息对话框 ----------------
        #dlg = wx.MessageDialog(None, 'Try to Choose!', u'请选择', wx.YES_NO | wx.ICON_QUESTION)
        # 样式有：wx.YES_NO, wx.OK, wx.CANCEL, ICON_QUESTION(会显示一个问号云）
        #result = dlg.ShowModal() #对话框关闭之前，别的窗口不能影响用户时间
        #dlg.Destroy()
    
    # ---------------- 处理函数 ----------------    
    def OnCloseMe(self, event):
        self.timer.Stop()
        del self.timer
        self.Close(True)
        
    def OnSave(self, event):
        #if not self.filename:
            self.OnSaveAs(event)
        #else:
        #   self.SaveFile()

    wildcard = "Log files (*.log)|*.log|All files (*.*)|*.*"
    def OnSaveAs(self, event):
        dlg = wx.FileDialog(self, "Save Log...", os.getcwd(), 
                            style=wx.SAVE | wx.OVERWRITE_PROMPT,
                            wildcard=self.wildcard)
        if dlg.ShowModal() == wx.ID_OK: # 必须调用dlg.ShowModal()方法
            filename = dlg.GetPath()
            print '%s' %filename
            if not os.path.splitext(filename)[1]: #不懂
                filename = filename + '.log'
            self.filename = filename
            self.SaveFile()
            #self.setTitle(self.title + '--' + self.filename)
            self.statusBar.SetStatusText(self.filename, 0)
        dlg.Destroy()

    def SaveFile(self):
        if self.filename:
            data = "test for save file"
            f = open(self.filename, 'w')
            f.write(data)
            f.close()

    def ShowAbout(self, event):
        # First we create and fill the info object
        info = wx.AboutDialogInfo()
        info.Name = u"工作台"
        info.Version = "0.0.1 based on wxPython" + wx.VERSION_STRING
        info.Copyright = "(C) 2012 Chandler Wang"
        info.Description = u"我的第一个wxPython程序"
        info.WebSite = ("http://code.google.com/p/bspworkbench/", "BSPWorkBench")
        info.Developers = [ "Chandler Wang",
                            "wxPython Book",
                            "Internet" ]
        # change the wx.ClientDC to use self.panel instead of self
        #info.License = wordwrap(licenseText, 500, wx.ClientDC(self.panel))
        # Then we call wx.AboutBox giving it that info object
        wx.AboutBox(info)

    def ShowHelp(self, event):
        dlg = SketchAbout(self)
        dlg.ShowModal()
        dlg.Destroy()

    def Notify(self):
        t = time.localtime(time.time())
        st = time.strftime("%d-%b-%Y   %I:%M:%S", t)
        self.SetStatusText(st, 2)


# 应用类
class WorkbenchAPP(wx.App):
    
    def OnInit(self):
        #self.frame = TopFrame(parent=None, title='WorkBench') #最好是啥都不传
        self.frame = TopFrame(None)
        self.frame.Show()
        return True

if __name__ == '__main__':
    app = WorkbenchAPP(False)
    app.MainLoop()